package com.leyou.task.job;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.RocketMQConstants.TAGS.ORDER_OVERTIME_TAGS;
import static com.leyou.common.constants.RocketMQConstants.TOPIC.ORDER_TOPIC_NAME;

@Component
@Slf4j
public class CleanOvertimeOrderTask {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 0 * * 1 ?") // 每小时执行一次
//    @Scheduled(cron = "0 0/1 * * * ?") // TODO 为了测试每分钟执行一次
//    @Scheduled(cron = "0/30 * * * * ?") // TODO 为了测试同步锁每两秒执行一次
    public  void cleanOvertimeOrder(){

        RLock lock = redissonClient.getLock("task_order");//获取锁 上锁
        boolean b = lock.tryLock(); //判断是否上锁成功
        if(b){
            try {
//                rocketMQTemplate.convertAndSend(ORDER_TOPIC_NAME+":"+ORDER_OVERTIME_TAGS,"开始清理无效订单");
                log.debug("获取锁成功，定时任务发送成功");
            } catch (MessagingException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
//                log.debug("锁成功释放");
            }
        }else{
            log.debug("获取锁失败");
        }
    }


}
